// pages/loupan/detail.js
var app = getApp();
var WxParse = require('../../utils/wxParse/wxParse.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: '',
    type: '',
    detail: '',
    newhouseBuilding: '',
    moretext: "点击查看更多",
    showmore: false,
    liked: false,
    imglist: [],
    wuyetype: '', // 物业类型
    wenda: [],
    isDesc: '', //楼盘详情
    isDisconuntInfo: '', //优惠信息
    IsDiscountinfo: false, //是否展示优惠信息
    isShowkefu: true, //客服
    currentId: '',
    StartTime: '',
    EndTime: '',
    modalName: '',
    picker: [
      '男', '女'
    ],
    value: '男',
    name: '',
    tel: '',
    huxingimg: '',
    xiangqingmore: '点击查看更多',
    xinagqingshow: false,
    opid: '',
    isApartment:true,
    agentList:[],
    adviserList:[],
    isadviser:null,
    reserveState:0,
    advertList: '',
    advertIndex: null,
    autoplay: true,
    follows: null,
    follow_count: 0,
    follow_user_id: 0,
    newslist: []
  },

  /**
   * 生命周期函数--监听页面加载
   */

  morexiangqing() {
    var show = this.data.xinagqingshow;

    if (show == true) {
      console.log(show)
      this.setData({
        xinagqingshow: false,
        xiangqingmore: '点击查看更多'
      })
    } else if (show == false) {
      console.log(show)
      this.setData({
        xinagqingshow: true,
        xiangqingmore: '点击收起'
      })
    }
  },
  onLoad: function(options) {
    this.getAdvert(null)
    //options['scene'] = '1400007710_1'
    var opid = wx.getStorageSync('user_new');
    // if (!opid) {
    //   wx.showModal({
    //     title: '提示',
    //     content: '授权后可以查看楼盘信息，方便本平台提供更多优质服务',
    //     success(res) {
    //       if (res.confirm) {
    //         console.log('用户点击确定')
    //         setTimeout(function () {
    //           wx.switchTab({
    //             url: '/pages/member/index',
    //           });
    //         }, 500)
    //       } else if (res.cancel) {
    //         setTimeout(function () {
    //           wx.switchTab({
    //             url: '/pages/index/index',
    //           });
    //         }, 500)
    //       }
    //     }
    //   })
    //   return;
    // }
    var that = this;
    var follow_user_id = '';
    if (options.scene == undefined) {

      var id = options.id
      if (options.follow_user_id != undefined) {
        follow_user_id = options.follow_user_id
        this.setData({
          follow_user_id: options.follow_user_id
        })

        wx.setStorageSync('referrer', follow_user_id)
      }

    } else {

      var scene = options.scene;
      scene = scene.split('_')

      if (scene.length > 1) {
        follow_user_id = scene[1]
      }

      var id = scene[0];

    }

    this.followAndList(id, follow_user_id)

    that.setData({
      id: id,
      // type: options.type,
      opid: opid
    })
    that.detail();

    this.news()
  },
  tel(e) {
    var tel = e.currentTarget.dataset.tel;
    wx.makePhoneCall({
      phoneNumber: tel // 仅为示例，并非真实的电话号码
    })
  },
  detail() {
    wx.showLoading({
      title: '加载中',
    })
    var id = this.data.id;
    var that = this;
    var opid = wx.getStorageSync('user_new');
    opid = opid != '' ? opid: 'null';
    app.core('get', 'get_houses_detail/id/' + id + '/open_id/' + opid + '', {}, (res) => {
      console.log(res)
      //有优惠信息的时候展示，没有就不展示
      wx.hideLoading()

      if (res.data.discountInfo) {
        that.setData({
          IsDiscountinfo: true,
          isShowkefu: true,
          isDisconuntInfo: res.data.discountInfo
        });
      } else {
        that.setData({
          IsDiscountinfo: false,
          isShowkefu: true
        });
      }

      if (res.data.newhouse_choice) {
        that.setData({
          reserveState:1
        });
      } else {
        that.setData({
          reserveState:0
        });
      }

      var article = res.data.newhouse_project_extend.projectIntro;
      WxParse.wxParse('article', 'html', article, that, 5);
      var newres = res.data;
      var wuyetype = res.data.propertyType;
      switch (wuyetype) {
        case "-1-3-":
          wuyetype = "-住宅-写字楼-"
          break;
        case "-1-2-":
          wuyetype = "-住宅-商铺-"
          break;
        case "-1-2-3":
          wuyetype = "-住宅-商铺-写字楼-"
          break;
        case "-2-3-":
          wuyetype = "-商铺-写字楼-"
          break;
        case "-1-":
          wuyetype = "-住宅-"
          break;
      }

      var renovateState = res.data.renovateState;
      var ressss = ''
      switch (renovateState) {
        case 1:
          ressss = "毛坯"
          break;
        case 2:
          ressss = "简装"
          break;
        case 3:
          ressss = "精装"
          break;

      }
      console.log(res.data, 11222)


      var markers =[{
        iconPath: "../../static/images/icon/map.png",
        id: 0,
        latitude: res.data.latitude,
        longitude: res.data.longitude,
        width: 50,
        height: 50
      }];



      that.setData({
        wuyetype: wuyetype,
        detail: res.data,
        newhouseBuilding: res.newhouseBuilding,
        liked: res.hasCollect,
        renovateState: ressss,
        markers: markers
      })

      var imglists = [];
      var huxingimg = [];
      for (var i = 0; i < res.data.newhouse_house_type.length; i++) {
        huxingimg.push(res.data.newhouse_house_type[i].photoPath)
      }

      if (res.data.buildNoPhoto != '') {
        imglists.push(res.data.buildNoPhoto);
      }
      if (res.data.effectPhoto != '') {
        imglists.push(res.data.effectPhoto);
      }
      if (res.data.sandPhoto != '') {
        imglists.push(res.data.sandPhoto);
      }
      if (res.data.trafficPhoto != '') {
        imglists.push(res.data.trafficPhoto);
      }

      if (res.albums.length > 0) {
        for (var j = 0; j < res.albums.length; j++) {
          imglists.push(res.albums[j])
        }
      }

      that.setData({
        imglist: imglists,
        huxingimg: huxingimg
      })

      var x = res.data.loupan_wenda;
      var wenda = [];
      for (var i = 0; i < x.length; i++) {
        if (x[i].p_wenda_id == 0) {
          wenda.push(x[i])
        }
      }
      that.setData({
        wenda: wenda
      })
      console.log(huxingimg)
      if (huxingimg.length == 0) {
        that.setData({
          isApartment: false
        })
      }
    })
  }, // 获取详情
  btnliked() {

    var that = this;
    var liked = that.data.liked;
    if (liked == false) {
      that.liked()
    } else {
      that.dislike()
    }
  },
  liked() {
    var opid = wx.getStorageSync('user_new');
    var id = this.data.id;
    var liked = this.data.liked;

    app.core('get', 'create_user_collect/open_id/' + opid + '/type/1/lid/' + id + '', '', (res => {
      this.setData({
        liked: true,
      })
      console.log(this.data.liked)
      wx.showToast({
        title: '收藏成功',
        icon: 'none',
        duration: 1000
      })
    }))


  }, // 收藏
  dislike() {

    var that = this;
    var id = that.data.id;
    var like = that.data.liked;
    var opid = wx.getStorageSync('user_new');

    app.core('get', 'cancel_user_collect/open_id/' + opid + '/type/1/lid/' + id + '', "", (res => {
      this.setData({
        liked: false,
      })
      console.log(this.data.liked)
      wx.showToast({
        title: '取消收藏',
        icon: 'none',
        duration: 1000
      })
      // that.setData({
      //   liked: false
      // })
    }))


  }, // 取消收藏

 //预览图片
  previewImagess(e) {
    var current = e.target.dataset.src;
    console.log(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: this.data.imglist
    })

  },
  previewImage(e) {
    var current = e.target.dataset.src;
    console.log(current);
    wx.previewImage({
      current: current, // 当前显示图片的http链接
      urls: this.data.huxingimg
    })

  }, //预览图片
  addmore() {
    var show = this.data.showmore;

    if (show == true) {
      console.log(show)
      this.setData({
        showmore: false,
        moretext: '点击查看更多'
      })
    } else if (show == false) {
      console.log(show)
      this.setData({
        showmore: true,
        moretext: '点击收起'
      })
    }

  },
  // 经纪人 复制微信
  copywx(e) {
    console.log(e.target.dataset.id)
    let id = e.target.dataset.id
    let agentList = this.data.agentList
    let wxchat = agentList[id].wechatId
    console.log(wxchat)
    wx.setClipboardData({
      //准备复制的数据
      data: wxchat,
      success: function (res) {
        wx.showToast({
          title: '复制成功，添加经纪人后获取更多置业消息',
          icon: 'none',
          duration: 1000
        })
      }
    });
  },
  //经纪人 拨号
  dial(e) {
    console.log(e.target.dataset.phone)
    var mobile = e.target.dataset.phone
    wx.showModal({
      title: '系统提示',
      content: '确定要联系 ' + mobile + ' 号码吗',
      success(res) {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: mobile
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  // 点击加载更多
  share(e) {
    var id = this.data.id;
    // var id = e.currentTarget.dataset.id
    console.log(id)
   wx.navigateTo({
    //  url: '/pages/poster/index?id='+id,
     url: `/pages/poster/index?id=${id}`
   })
  },
  // 分享转发
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    let open_id = wx.getStorageSync('user_new')
    app.core('get', 'getUserInfo?open_id=' + open_id, '', (res) => {
      console.log(res.data.adviser_id)
      let isadviser = res.data.adviser_id
      this.setData({
        isadviser: isadviser
      })
    })
    var timestamp = Date.parse(new Date()); //进入页面的时间戳
    var Stimestamp = timestamp / 1000;
    this.setData({
      StartTime: Stimestamp
    });
    let siteId = app.globalData.cityCode
    var projectId = this.data.id;
    console.log(siteId)
    app.core('get', 'getAgentAndAdviser', { siteId: siteId, limit: 10, type: 1, projectId: projectId },(res) => {
      console.log(res)
      if(res.resultCode === 200) {
        this.setData({
          agentList: res.data.agentList,
          adviserList:res.data.adviserList
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    var timestamp = Date.parse(new Date()); //离开页面的的时间戳
    var Etimestamp = timestamp / 1000;
    this.setData({
      EndTime: Etimestamp
    });
    app.core('post', 'create_data_statistics', {
        // data 部分
        'type': 1,
        'visit_time': this.data.EndTime - this.data.StartTime,
        'read_id': this.data.id,
        'open_id': wx.getStorageSync('user_new')
      }, (res) => {
        console.log(res)
      },
      (err) => {
        console.log(err)
      }
    )
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var imgurl = this.data.detail.buildNoPhoto;

    var user = wx.getStorageSync('user')
    var follow_user_id = 0
    if (user && user.user_id) {
      follow_user_id = user.user_id
    }

    return {
      title: this.data.detail.projectName,
      path: 'pages/loupan/detail?id=' + this.data.id + '&follow_user_id=' + follow_user_id,
      imageUrl: imgurl

    }
  },


  // 客服
  gocontent: function() {
    wx.makePhoneCall({
      phoneNumber: '400-887-1216'
    })
  },
  // 顾问
  goadviser() {
    let detail = this.data.detail.data_name_txt
    let id = this.data.detail.id
    console.log(id)
    wx.navigateTo({
      url: '/pages/adviser/adviser?detail=' + detail + '&id='+ id,
    })
  },
  sqyh() {
    this.showModal()
  }, // 申请优惠
  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target,
    })
  },
  pickerchange(e) {
    console.log(e);
    var name = this.data.picker[e.detail.value]
    this.setData({
      value: name
    })
  },

  getname(e) {
    this.setData({
      name: e.detail.value
    })

  },
  gettel(e) {
    this.setData({
      tel: e.detail.value
    })

  },

  hideModal(e) {

    this.setData({
      modalName: null
    })
  },
  submitmodal() {
    var project_id = this.data.houseid;
    var that = this;
    var name = that.data.name;
    var phone = that.data.tel;
    var sex = that.data.value;
    if (name == '') {
      wx.showToast({
        title: '请输入姓名',
        duration: 1000,
        icon: 'none'
      });
      return;
    } else if (phone == '') {
      wx.showToast({
        title: '请输入手机号码',
        duration: 1000,
        icon: 'none'
      })
    } else {
      app.core('post', 'order_project', {
        name: name,
        phone: phone,
        type: 1,
        project_id: project_id,
        sex: sex
      }, (res => {
        this.setData({
          modalName: null
        })
        wx.showToast({
          title: '已申请优惠',
          duration: 1000,
          icon: 'none'
        })
      }))
    }
  },

// 跳转在线订房
  toSelectHouse(){
    var id = this.data.id;
    wx.navigateTo({
      url: './zaixiandetail?id=' + id,
    })
  },

  // 置业顾问拨打电话
  phone_now: function (e) {
    // console.log(e.currentTarget.dataset)
    let phone = e.currentTarget.dataset.phone
    console.log(phone)
    wx.makePhoneCall({
      phoneNumber: phone
    })
  },


  // 更多置业顾问
  bindMore(e){
    var flag = e.currentTarget.dataset.flag;
    let detail = this.data.detail.data_name_txt
    let id = this.data.detail.id
    console.log(id)
    wx.navigateTo({
      url: '/pages/adviser/adviser?detail=' + detail + '&id=' + id+'&flag='+flag,
    })
  },

  /**
   * 打开位置
   */
  bindOpenMap(e){
    let longitude = this.data.detail.longitude
    let latitude = this.data.detail.latitude
    wx.openLocation({
      latitude,
      longitude,
      scale: 18
    })
  },

  /**
   * VR航拍看房
   */
  bindVr(){
      if (this.data.detail.vr != '' && this.data.detail.vr != undefined) {
          var vr = this.data.detail.vr
          wx.navigateTo({
              url: '/pages/loupan/vr/index?vr=' + encodeURIComponent(vr),
          })
      } else {
          wx.showModal({
              title: ' 提示',
              content: '正在拍摄中 敬请期待',
          })
      }
  },

    /**
   * 置业顾问 立即咨询
   */
  bindAdviserChat(e){
    var opid = wx.getStorageSync('user_new');
    var id = e.currentTarget.dataset.id;
    if (!opid){
      wx.showModal({
        title: '提示',
        content: '授权后可以查看楼盘信息，方便本平台提供更多优质服务',
        success(res) {
          if (res.confirm) {
            console.log('用户点击确定')
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/member/index',
              });
            }, 500)
          } else if (res.cancel) {

          }
        }
      })
    }else if(opid == id){
        wx.showToast({
          title: '不可给自己留言',
        })
    }else{
      wx.navigateTo({
        url: '../adviser/chat/chat?id=' + id,
      })
    }

  },

  //广告获取
  getAdvert: function(cityCode) {
    var vm = this;
    var isNumsList=null;
    let setid = cityCode || wx.getStorageSync('cityCode')
    app.core('get', 'get_loupan_detail_banner_advert/site_id/' + setid + '','', (res) => {
          // console.log(res);
          vm.setData({
            advertList: res.data,
          });
        },
        (err) => {
          console.log(err)
        }
    )
  },

  bindplay: function () {
    this.setData({
      autoplay: false
    })
  },

  bindpause: function () {
    this.setData({
      autoplay: true
    })
  },

  handleKanfangtuan: function () {
    wx.navigateTo({
      url: '/pages/kanfangtuan/index?houseId=' + this.data.id + '&title=' + this.data.detail.projectName,
    })
  },

  followAndList: function(id, follow_user_id) {
    var open_id = wx.getStorageSync('user_new');
    app.core('get', 'user/followByType', {id: id, open_id: open_id, follow_user_id: follow_user_id, type: 'newhouse'}, (res) => {
      console.log(res)

      this.setData({
        follows: res.data.follows,
        follow_count: res.data.count,
      })
    })
  },

  news(){
    // wx.showLoading({
    //   title: '正在加载',
    // })
    var that = this;
    var num = 1;
    var list =that.data.newslist;
    var setid = app.globalData.cityCode;
    app.core('get', 'article/getRecommendArticles?siteId=' + setid +'&id=' + this.data.id ,"",(res=>{
      that.setData({
        newslist: res.data,
      })
    }))
  },

  //获取资讯列表
  getLocalTime(date) {
    // return new Date(parseInt(nS) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ');
    var date = new Date(date * 1000);//如果date为13位不需要乘1000
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
    var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
    var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
    return Y + M + D + h + m + s;


  }, // 转换时间戳

  bindNewsMore() {
    wx.switchTab({
      url: '/pages/information/index'
    })
  },

  handleFollow(e) {
    wx.navigateTo({
      url: '/pages/loupan/follow/index?id=' + this.data.id + '&type=newhouse'
    })
  }

})
